import {
  HTTP_REQUEST_URL,
  HEADER,
  TOKEN_HEADER
} from '@/config/app';
import store from '@/store/m_user.js'

function fullUrl(url) {
  /* 判断url是否为完整路径 */
  return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
}

//表单序列化
function serialize(data) {
  let list = [];
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&');
};

/**
 * 发送请求
 */
export default function request(config = {}) {
  config.url = fullUrl(config.url) ? config.url : HTTP_REQUEST_URL + config.url
  config.data = config.data || {}
  config.params = config.params || {}
  config.headers = Object.assign(HEADER, config.headers)
  config.method = config.method || 'GET'
  config.method = config.method.toUpperCase()
  config.showLoading = config.showLoading === undefined ? false : config.showLoading

  if (config.showLoading) {
    // 显示加载中 效果
    uni.showLoading({
      title: "加载中",
      mask: true
    });
  }

  if (store.state.token) config.headers[TOKEN_HEADER] = 'bearer ' + store.state.token;
  
    config.headers['lat'] = store.state.currentLocation.latitude;
	config.headers['lng'] = store.state.currentLocation.longitude;
	
  if (config.method === 'POST' && JSON.stringify(config.params) != '{}') {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    config.data = config.params;
  } else if (config.method === 'POST') {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
  }
  return new Promise((reslove, reject) => {
    uni.request({
      url: config.url,
      method: config.method,
      header: config.headers,
      data: config.method === 'GET' ? config.params : config.data,
      success: (res) => {

        //获取状态码
        const status = res.data.code || res.status || res.statusCode;
        const message = res.data.msg || res.data.error_description || '未知错误';

        //如果是401则跳转到登录页面
        if (status === 401 && !store.state.token) {
          uni.navigateTo({
            url: '/pages/login/login'
          })
          //  关闭正在等待的图标
          if (config.showLoading) {
            uni.hideLoading();
          }
        } else if (status !== 200) {
          reject(message);
          if (config.showLoading) {
            uni.hideLoading();
          }
        } else {
          reslove(res.data);
          if (config.showLoading) {
            uni.hideLoading();
          }
        }
      },
      fail: (msg) => {
        reject('请求失败');
        if (config.showLoading) {
          uni.hideLoading();
        }
      }
    })
  });
}
